﻿using System;
using System.Collections.Generic;
using System.Text;

using Microsoft.Data.Sqlite;

using Spatial4n.Context;
using Spatial4n.Distance;
using Spatial4n.Shapes;

using static Lucene.Net.Util.Fst.Util;

namespace iTool.Cloud.Database.iToolService
{
    internal class CustomFunctionStructure
    {
        static Func<double?, double?, double?, double?, double?> distanceFunction;

        static CustomFunctionStructure()
        {
            distanceFunction = (double? x1, double? y1, double? x2, double? y2) =>
            {
                if (x1 is null || y1 is null || x2 is null || y2 is null)
                {
                    return null;
                }

                IPoint iPoint = SpatialContext.Geo.MakePoint((double)x1, (double)y1);
                double distDEG = SpatialContext.Geo.CalcDistance(iPoint, (double)x2, (double)y2);
                double distance = DistanceUtils.Degrees2Dist(distDEG, DistanceUtils.EarthMeanRadiusKilometers);
                return distance;
            };
        }

        readonly SqliteConnection connection;
        readonly List<string> customFunctions;

        public CustomFunctionStructure(SqliteConnection connection, List<string> customFunctions) 
        {
            this.connection = connection;
            this.customFunctions = customFunctions;
        }


        public void Excuter() 
        {
            foreach (var item in customFunctions)
            {
                switch (item)
                {
                    case "distance":
                        this.distance();
                        break;
                }
            }
        }

        void distance() 
        {
            this.connection.CreateFunction("distance", distanceFunction);
        }

    }
}
